package cn.akwangl.interceptor;

import cn.akwangl.pojo.User;
import cn.hutool.core.util.IdUtil;
import org.slf4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 系统拦截器.
 *
 * @author youyongkun
 * @date 2022/5/16 19:32
 */
public class SystemInterceptor implements HandlerInterceptor {

    private static final String Authentication = "token";

    private static final Logger log = LoggerWrapper.getLogger(SystemInterceptor.class);

    /**
     * 系统日志组件.
     *
     * @author 阿坤同学
     * @date 2022/5/29 12:02
     * @since 0.0.4
     */
    private static final LoggerWrapper LOGGER_WRAPPER = new LoggerWrapper(SystemInterceptor.class);

    /**
     * 全局用户信息.
     *
     * @author 阿坤同学
     * @date 2022/5/29 13:05
     * @since 0.0.4
     */
    private static final GlobalUser GLOBAL_USER = new GlobalUser();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        LOGGER_WRAPPER.setGlobalSysLogId(IdUtil.getSnowflakeNextIdStr());
        String token = request.getHeader(Authentication);
        GLOBAL_USER.setGlobalUser(token);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        GLOBAL_USER.cleanGlobalUser();
        LOGGER_WRAPPER.cleanGlobalSysLogId();
    }

    /**
     * 获取全局User对象.
     *
     * @return User
     * @author 阿坤同学
     * @date 2022/5/29 13:07
     * @since 0.0.4
     */
    public static User getGlobalUser() {
        return GLOBAL_USER.getGlobalUser();
    }
}